import {Injectable} from '@angular/core';
import {RouterService} from '@kylin/router';
import {UserService} from '@kylin/core';
import {CacheService} from '@kylin/cache';
import {environment} from '../../environments/environment';
import {HttpService} from '@kylin/http';
import * as _ from 'lodash';

@Injectable()
export class HomeService {

    msgData: { notifications: any[], count: number } = {notifications: [], count: 0};
    msgDataInterval: any;

    constructor(private routerService: RouterService,
                private userService: UserService,
                private http: HttpService,
                private cacheService: CacheService
    ) {
    }

    /**
     * 登出
     */
    logout() {
        this.routerService.navigate('/login');
        this.cacheService.remove('siderData');
        this.cacheService.remove('token');
        this.userService.clearUser();
    }

    /**
     * 用于在进入home页面时候验证用户是否已经登陆,如果没有登陆,那么跳转到登陆页面
     */
    getSidebarMenuData() {
        if (false) {
            return this.cacheService.get('siderData').menuList;
        } else {
            return [
                {
                    name: '系统首页',
                    url: '',
                    icon: 'home',
                    childMenu: [
                        {
                            name: '系统首页',
                            url: '/home/system-home-page/home-page',
                            childMenu: []
                        },
                        {
                            name: '账户设置',
                            url: '/home/system-home-page/set-account',
                            childMenu: []
                        },
                        {
                            name: '登录日志',
                            url: '/home/system-home-page/login-log',
                            childMenu: []
                        }
                    ]
                },
                {
                    name: '系统设置',
                    url: '',
                    icon: 'setting',
                    childMenu: [
                        {
                            name: '用户管理',
                            url: '/home/system-settings/user-management',
                            childMenu: []
                        },
                        {
                            name: '城市管理',
                            url: '/home/system-settings/city-management',
                            childMenu: []
                        },
                        {
                            name: '数据字典',
                            url: '/home/system-settings/dictionary',
                            childMenu: []
                        },
                        {
                            name: '操作日志',
                            url: '/home/system-settings/operation-log',
                            childMenu: []
                        }
                    ]
                },
                {
                    name: '任务报送',
                    url: '',
                    icon: 'copy',
                    childMenu: [
                        {
                            name: '任务报送',
                            url: '/home/task-submit',
                            childMenu: []
                        },
                    ]
                },
                {
                    name: '任务审核',
                    url: '',
                    icon: 'edit',
                    childMenu: [
                        {
                            name: '任务审核',
                            url: '/home/task-check/task-check-list',
                            childMenu: []
                        },
                    ]
                },
                {
                    name: '任务查询',
                    url: '',
                    icon: 'search',
                    childMenu: [
                        {
                            name: '任务查询',
                            url: '/home/task-query',
                            childMenu: []
                        },
                    ]
                },
                {
                    name: '信息报送',
                    url: '',
                    icon: 'snippets',
                    childMenu: [
                        {
                            name: '人工饲草基地种植情况',
                            url: '/home/information-submis/artificial',
                            childMenu: []
                        },
                        {
                            name: '牧草良种繁育基地生产情况',
                            url: '/home/information-submis/grass',
                            childMenu: []
                        },
                        {
                            name: '饲草种植加工及商品草销售情况',
                            url: '/home/information-submis/forage',
                            childMenu: []
                        }
                    ]
                },
                {
                    name: '信息审核',
                    url: '',
                    icon: 'form',
                    childMenu: [
                        {
                            name: '人工饲草基地种植情况审核',
                            url: '/home/information-check/check-artificial',
                            childMenu: []
                        },
                        {
                            name: '牧草良种繁育基地生产情况审核',
                            url: '/home/information-check/check-grass',
                            childMenu: []
                        },
                        {
                            name: '饲草种植加工及商品草销售情况审核',
                            url: '/home/information-check/check-forage',
                            childMenu: []
                        }
                    ]
                },
                {
                    name: '统计报表',
                    url: '',
                    icon: 'line-chart',
                    childMenu: [
                        {
                            name: '专题统计',
                            url: '/home/statistical',
                            childMenu: []
                        }
                    ]
                },
                {
                    name: '数据查询',
                    url: '',
                    icon: 'search',
                    childMenu: [
                        {
                            name: '人工饲草种植情况',
                            url: '/home/data-query/artificial',
                            childMenu: []
                        },
                        {
                            name: '牧草良种繁育基地生产情况',
                            url: '/home/data-query/grass',
                            childMenu: []
                        },
                        {
                            name: '饲草种植加工及商品草销售情况',
                            url: '/home/data-query/forage',
                            childMenu: []
                        }
                    ]
                }
            ];
        }
    }


    fetchMsgDataInit() {
        if (!this.msgDataInterval) {
            this.fetchMsgData();
            this.msgDataInterval = setInterval(() => {
                this.fetchMsgData();
            }, 18000);
        }

    }

    clearMsgDataInterval() {
        if (this.msgDataInterval) {
            clearInterval(this.msgDataInterval);
            this.msgDataInterval = null;
        }
    }

    private fetchMsgData() {

        this.http.get('/grass/statusCount')
            .then(res => {
                const data = this.mapObject(res.result, (value, key) => {
                    return this.msgDataHandle(value, key);
                });

                const taskApplyData = [{name: 'task-submit', data: data['apply'], path: '/home/task-submit'}];
                const infoSubmitData = [
                    {name: '人工饲草基地种植情况', data: data['artificial'], path: '/home/information-submis/artificial'},
                    {name: '牧草良种繁育基地生产情况', data: data['pasture'], path: '/home/information-submis/grass'},
                    {name: '饲草种植加工及商品草销售情况', data: data['grassSale'], path: '/home/information-submis/forage'}
                ];

                const notifications = [{title: 'task-submit', data: taskApplyData}, {
                    title: 'information-submis',
                    data: infoSubmitData
                }];

                let count = 0;
                notifications.map(child => {
                    child.data.map(i => {
                        i.data.map(e => {
                            if (e.key !== 'finished') {
                                count += e.value;
                            }
                        });
                    });
                });
                this.msgData = {count, notifications};

            })
            .catch(err => {
                console.error(`获取消息失败`);
                console.error(err);
                this.msgData = {notifications: [], count: 0};
            });
    }

    private msgDataHandle(data, targetKey) {

        let _result = this.mapObject(data, (value, key) => {
            let target = {};
            switch (key) {
                case 'finished':
                    target = {key, value, id: 4};
                    break;
                case 'waitCityHandle':
                    target = {key, value, id: 1};
                    break;
                case 'waitProvinceAgree':
                    target = {key, value, id: 3};
                    break;
                case 'waitProvinceHandle':
                    target = {key, value, id: 2};
                    break;
                case 'waitSubmit':
                    target = {key, value, id: 0};
                    break;
            }
            return target;
        });

        if (targetKey !== 'apply') {
            delete _result['waitProvinceAgree'];
        }
        _result = this.msgDataControl(_result);
        let targetArr = [];
        this.mapObject(_result, (i) => {
            targetArr[i['id']] = {key: i['key'], value: i['value']};
        });
        targetArr = _.without(targetArr, undefined);
        return targetArr;
    }

    private msgDataControl(data) {
        const roleName = this.userService.getValue('roleName');
        const targetAttr = [];
        switch (roleName) {
            case 'areaAdmin':
                break;
            case 'cityAdmin':
                targetAttr.push('waitSubmit');
                break;
            case 'provinceAdmin':
                targetAttr.push('waitSubmit');
                targetAttr.push('waitCityHandle');
                break;
            case 'sysadmin':
                targetAttr.push('waitSubmit');
                targetAttr.push('waitCityHandle');
                break;
        }

        if (targetAttr.length > 0) {
            targetAttr.map(i => {
                delete data[i];
            });
        }
        return data;
    }


    private mapObject(obj: {}, func: Function) {
        const target = {};
        Object.keys(obj).forEach(key => {
            const funcResult = func(obj[key], key);
            if (funcResult) {
                Object.assign(target, {[key]: funcResult});
            }
        });
        return target;
    }

}
